package com.orange.common.util

import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.Uri
import com.blankj.utilcode.util.ActivityUtils


/**
 *  created by Orange on 2022/12/9 15:54
 *  商店跳转工具类
 */
object AppStoreUtils {
    //老版包名
    private const val GOOGLE_PLAY_STORE_PACKAGE_NAME_OLD = "com.google.market"

    //新包名
    private const val GOOGLE_PLAY_STORE_PACKAGE_NAME_NEW = "com.android.vending"

    /**
     * 根据包名判断是否安装
     */
    fun isAppInstalled(context: Context, packageName: String?): Boolean {
        var packageInfo: PackageInfo?
        try {
            packageInfo = context.packageManager.getPackageInfo(packageName!!, 0)
        } catch (e: PackageManager.NameNotFoundException) {
            packageInfo = null
            e.printStackTrace()
        }
        return packageInfo != null
    }

    /**
     * 是否有安装 google play 商店
     * @return
     */
    fun isGooglePlayAvailable(context: Context): Boolean {
        return isAppInstalled(context, GOOGLE_PLAY_STORE_PACKAGE_NAME_OLD) ||
                isAppInstalled(context, GOOGLE_PLAY_STORE_PACKAGE_NAME_NEW)
    }

    /**
     * 跳转到 Google Play
     * uri = "market://details?id=" + getPackageName()
     */
    fun jumpGooglePlay(
        context: Context = ActivityUtils.getTopActivity(),
        uri: String = "market://details?id=$context.packageName"
    ): Boolean {
        return try {
            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri))
            intent.setPackage("com.android.vending")
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    /**
     * 外部浏览器打开链接
     * @param url
     */
    fun openBrowser(context: Context = ActivityUtils.getTopActivity(), url: String) {
        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
        context.startActivity(intent)
    }
}